package vue.panels;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.DefaultStyledDocument;
import javax.swing.text.Style;
import javax.swing.text.StyleContext;

import model.PseudoListModel;

import vue.Ui;
import controler.Joueur;
import controler.Protocol;
import controler.ProtocolException;
import vue.components.*;
/**
 * <p>Title: vue.CamembertPanel </p>
 *
 * <p>
 * 	Description: Cette classe gere l'affichage du panneau de chat
 * </p>
 *
 * <p>Copyright: (c) 2008 FSSIM</p>
 *
 * <p>Company: FSSImock</p>
 *
 * @author Antoine Farnault
 * @author Augustin Couette
 * @version 1.0
 */
public class ChatPanel extends TPPanel {

	private static final long serialVersionUID = 1L;
	
	// Variables declaration
    public TPTextPane chatText;
    private TPButton envoyerButton;
    private JScrollPane jScrollPane1;
    private JScrollPane jScrollPane2;
    public TPTextField msgText;
    public JList pseudoList;
    public PseudoListModel pseudoListModel = new PseudoListModel();
    DefaultStyledDocument doc = new  DefaultStyledDocument();
    Style racine = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
    
    //Vector<String> listeJoueurs;
    public Ui ui;
    public String nomTable; // le nom de la table qui contient le chat. Est = "Salle" si c'est le general
    
    // End of variables declaration
	
	/** Creates new form ChatPanel */
    public ChatPanel(Ui ui,String nomTable) {
        this.ui = ui;
        this.nomTable = nomTable;
        initComponents();
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     */
    private void initComponents() {
    	setName("chatPanel");
    	setTPTitle("Zone de chat");
        jScrollPane1 = new JScrollPane();
        chatText = new TPTextPane();
        
        envoyerButton = new TPButton();
        msgText = new TPTextField();
        msgText.setForeground(Joueur.couleur); // FIXME marche pas...
        jScrollPane2 = new JScrollPane();
        //listeJoueurs =  new Vector<String>();
        //pseudoList = new JList(listeJoueurs);
        pseudoList = new JList();
        pseudoList.setModel(pseudoListModel);
        pseudoList.setCellRenderer(new ListRenderer());

        msgText.addKeyListener(new KeyAdapter(){
        	public void keyPressed(KeyEvent evt){
        		msgTextButtonKeyPressed(evt);
        	}
        });
        
        chatText.setEditable(false);
        chatText.getDocument().addDocumentListener(new DocumentListener(){
			@Override
			public void changedUpdate(DocumentEvent e) {
				chatText.setCaretPosition(chatText.getDocument().getLength ());
			}
			@Override
			public void insertUpdate(DocumentEvent e) {
				chatText.setCaretPosition(chatText.getDocument().getLength ());
			}
			@Override
			public void removeUpdate(DocumentEvent e) {
				chatText.setCaretPosition(chatText.getDocument().getLength ());
			}
        });
        
        jScrollPane1.setViewportView(chatText);

        envoyerButton.setText("Envoyer");
        envoyerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                envoyerButtonActionPerformed(evt);
            }
        });
        envoyerButton.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                envoyerButtonKeyPressed(evt);
            }
        });
        
        jScrollPane2.setViewportView(pseudoList);

        GroupLayout layout = new GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE)
                    .addComponent(msgText, GroupLayout.Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 600, Short.MAX_VALUE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.LEADING)
                    .addComponent(envoyerButton, GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)
                    .addComponent(jScrollPane2, GroupLayout.DEFAULT_SIZE, 30, Short.MAX_VALUE)))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(GroupLayout.Alignment.LEADING)
            .addGroup(GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane2, 0, 0, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, GroupLayout.DEFAULT_SIZE, 100, Short.MAX_VALUE))
                .addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(GroupLayout.Alignment.BASELINE)
                    .addComponent(msgText, GroupLayout.PREFERRED_SIZE, 25, GroupLayout.PREFERRED_SIZE)
                    .addComponent(envoyerButton)))
        );
    }
    
    /**
     * Action quand on appuie sur le bouton Envoyer 
     * @param evt
     */
    private void envoyerButtonActionPerformed(ActionEvent evt) {
    	if(msgText.getText().length() == 0){ // on envoie pas de chaine vide
    		return;
    	}
    	try {
			Protocol.snd_chat(msgText.getText(), Joueur.name,nomTable,Joueur.colorToString(Joueur.couleur));
			msgText.setText("");
	        msgText.setFocusable(true);
		} catch (ProtocolException e) {
			e.printStackTrace();
		}
    }
    /**
     * Action quand on appuie sur la touche entree sur le bouton envoyer
     * @param evt
     */
    private void envoyerButtonKeyPressed(KeyEvent evt) {
    	if(evt.getKeyCode() == 10){ // appuie sur entree
    		envoyerButtonActionPerformed(null);
    	}
    }
    /**
     * Action quand on appuie sur la touche entree sur la zone de texte
     * @param evt
     */
    private void msgTextButtonKeyPressed(KeyEvent evt) {
    	if(evt.getKeyCode() == 10){ // appuie sur entree
    		envoyerButtonActionPerformed(null);
    	}
	}
    
    /**
     * Ajout d'un pseudo a la liste (graphiquement)
     * @param name
     */
	public void addToPseudoList(String name, Color couleur) {
		pseudoListModel.addElement(new ListItem(couleur,name));
		pseudoList.setModel(pseudoListModel);
		updateUI();
	}
	/**
	 * Supprime un pseudo de la liste
	 * @param name
	 */
	public void delToPseudoList(String name,Color couleur) {
		for (int i = 0; i < pseudoListModel.getSize(); i++) {
			ListItem tmp = (ListItem)pseudoListModel.getElementAt(i);
			if(tmp.value.equals(name)){ 
				pseudoListModel.remove(i);
				return;
			}
		}
	}
	/**
	 * Affiche le msg dans la zone de texte
	 * @param s le msg a afficher
	 */
	public void displayMsg(String prefix ,String s,Color c,boolean fromServseur){
		if(fromServseur){
			chatText.append(prefix, c, Color.white, true,false);
			chatText.append(s+"\n", c, Color.white, true,true);
		}
		else{
			chatText.append(prefix+" : ", c, Color.white, true,false);
			chatText.append(s+"\n", c, Color.white, false,true);
		}
	}
}
